<?php

/**
 * 从数据库导出数据到 PHP 文件
 */

$dbConfig = require 'config.php';
include 'lib/Db.class.php';

// ===================================================================

$tables = [
    'ims_wei_idiom_topic' =>
    [
        'text' => '题目',
        'fields' => 'keyword, key_index, alternatives, res_index, status, level'
    ]
];

// 如果有数据，则导出数据。如果没有数据，则导出空模板
$data = exportData($dbConfig, $tables);
foreach ($data as $table => $content) {
    $filename = "../output/export_data_{$table}.php";
    file_put_contents($filename, $content);
    echo '导出成功：', $filename, PHP_EOL;
}

function exportData($dbConfig, $tables)
{
    $data = [];
    $pdo = new Db($dbConfig);
    foreach ($tables as $table => $tableInfo) {
        // 查询数据
        $list = $pdo->query("select {$tableInfo['fields']} from {$table}");
        // 查询字段类型
        $allowColumns = array_map(function ($v) {
            return trim($v);
        }, explode(',', $tableInfo['fields']));
        $columnsTemp = $pdo->getColumns('', $table);
        $columns = [];
        foreach ($columnsTemp as $columnInfo) {
            if (in_array($columnInfo['COLUMN_NAME'], $allowColumns)) {
                $columns[$columnInfo['COLUMN_NAME']] = $columnInfo['DATA_TYPE'];
            }
        }
        $content = '';
        if ($list) {
            // ['name' => '一年级', 'level' => 1,],
            foreach ($list as $row) {
                $kvList = [];
                foreach ($row as $k => $v) {
                    $kvList[] = "'{$k}' => '{$v}'";
                }
                $content .= "\t[" . implode(',', $kvList) . '],' . PHP_EOL;
            }
        }
        $content = <<<tpl
    <?php
    /**
     * {$tableInfo['text']}
     */
    \$data = [
    {$content}
    ];
    return ['table' => '{$table}', 'text' => '{$tableInfo['text']}', 'truncate' => true, 'data' => \$data, 'append' => ['createtime' => date('Y-m-d H:i:s'), 'updatetime' => date('Y-m-d H:i:s'), 'status' => 1],];
    tpl;
        $data[$table] = $content;
    }
    return $data;
}
